<template>
    <div class="iframe-container">
        <iframe 
            v-if="path && !loadError" 
            :src="path" 
            class="iframe"
            @load="handleLoad"
            @error="handleError"
        ></iframe>
        <div v-if="loadError" class="error-container">
            <h3>无法加载页面</h3>
            <p>目标网站禁止在iframe中显示内容，这是网站的安全策略。</p>
            <p>您可以尝试：<a :href="path" target="_blank">在新窗口中打开页面</a></p>
        </div>
    </div>
</template>

<script setup>
import { ref, watch, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { useMenuStore } from '$aegisStore/menu'

const route = useRoute()
const menuStore = useMenuStore()

const path = ref('')
const loadError = ref(false)

const setPath = function () {
    const { key, sider_key: siderKey } = route.query

    const menuItem = menuStore.findMenuItem({
        key: 'key',
        value: siderKey ?? key
    })

    path.value = menuItem?.iframeConfig?.path ?? ''
    loadError.value = false // 重置错误状态
}

const handleLoad = function() {
    // iframe加载成功
    console.log('iframe loaded successfully')
}

const handleError = function() {
    // iframe加载失败
    loadError.value = true
    console.log('iframe failed to load')
}

watch([
    () => route.query.key,
    () => route.query.sider_key,
    () => menuStore.menuList,
], () => {
    setPath()
},{ deep: true })


onMounted(() => {
    setPath()
})

</script>

<style lang="less" scoped>
.iframe-container {
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.iframe {
    border: 0;
    width: 100%;
    height: 100%;
    overflow: hidden;
}

.error-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 100%;
    padding: 20px;
    text-align: center;
    
    h3 {
        color: #f56565;
        margin-bottom: 10px;
    }
    
    p {
        color: #4a5568;
        margin-bottom: 10px;
    }
    
    a {
        color: #3182ce;
        text-decoration: none;
        
        &:hover {
            text-decoration: underline;
        }
    }
}
</style>